<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">

      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="商户订单号" prop="merchantOrderNo" label-width="100px">
        <el-input v-model="queryParams.merchantOrderNo" placeholder="请输入商户订单号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="商品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
<!--      <el-form-item label="库龄" prop="storageAge">
        <el-input v-model="queryParams.storageAge" placeholder="请输入库龄" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <el-form-item label="库龄" >
        <el-input-number  :min="0"  v-model="queryParams.minStorageAge" @change="handleMinChange" />
        ~
        <el-input-number :min="0"  v-model="queryParams.maxStorageAge" @change="handleMaxChange" />
      </el-form-item>

      <el-form-item label="手机品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入手机品牌" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机型号" prop="model" label-width="100px">
        <el-input v-model="queryParams.model" placeholder="请输入手机型号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="机况类型" prop="model" label-width="100px">
        <el-select  style="width: 100%;" v-model="queryParams.conditionTypeCode"
                    placeholder="请选择机况类型" clearable>
          <el-option v-for="dict in getDictDatas(DICT_TYPE.condition_type
            )" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="IMEI" prop="imei">
        <el-input v-model="queryParams.imei" placeholder="请输入IMEI" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="入库时间" prop="inboundTime">
        <el-date-picker v-model="queryParams.inboundTime"  style="width: 240px"  value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="所在仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" filterable clearable placeholder="请选择所在仓库">
          <el-option v-for="warehouse in warehouseDatas" :key="parseInt(warehouse.id)" :label="warehouse.name"
                     :value="parseInt(warehouse.id)"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="机况" prop="subrackDesc">
        <el-input v-model="queryParams.subrackDesc" placeholder="请输入机况" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的发货数据
          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['pekingfish:storage-formal-warehouse:create']">新增</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                   v-hasPermi="['pekingfish:storage-formal-warehouse:import']">正式仓导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['pekingfish:storage-formal-warehouse:export']" >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" stripe border :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                     v-hasPermi="['pekingfish:storage-formal-warehouse:update']" v-if="scope.row.addPrice==0">编辑</el-button>
          <el-button size="mini" type="text" @click="doSomthing(scope.row,1)"
                     v-hasPermi="['pekingfish:storage-formal-warehouse:allot']" v-if="scope.row.isOutbound==0">调拨</el-button>
          <el-button size="mini" type="text" @click="doSomthing(scope.row,2)"
                     v-hasPermi="['pekingfish:storage-formal-warehouse:reportDamage']">报损</el-button>
          <el-button size="mini" type="text"  @click="handleView(scope.row,scope.index)"
                     v-hasPermi="['pekingfish:storage-formal-warehouse:detail']"
          >详细
          </el-button>
<!--          <el-dropdown  @command="(command) => handleCommand(command, scope.$index, scope.row)"
                        v-hasPermi="['pekingfish:storage-formal-warehouse:allot', 'pekingfish:storage-formal-warehouse:reportDamage']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="allot" size="mini" type="text"
                                v-hasPermi="['pekingfish:storage-formal-warehouse:allot']">调拨</el-dropdown-item>
              <el-dropdown-item command="reportDamage" size="mini" type="text"
                                v-hasPermi="['pekingfish:storage-formal-warehouse:reportDamage']">报损</el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>-->
        </template>
      </el-table-column>
      <el-table-column label="商品二编码" align="center" prop="headImg" min-width="150px">
        <template v-slot="scope">
          <image-preview :src="scope.row.qrCode" :width="40" :height="40"></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="productCode" width="180px"/>
      <el-table-column label="订单号" align="center" prop="orderNo" width="180px"/>
      <el-table-column label="商户订单号" align="center" prop="merchantOrderNo" width="180px"/>
      <el-table-column label="手机品牌" align="center" prop="brand" />
      <el-table-column label="手机型号" align="center" prop="model" width="150px"/>
      <el-table-column label="IMEI" align="center" prop="imei"  width="150px"/>
      <el-table-column label="型号类型" align="center" prop="modelType" width="100px"/>
      <el-table-column label="所在仓库" align="center" prop="warehouseName" width="120px"/>
      <el-table-column label="机况类型" align="center" prop="conditionTypeName" width="120px"/>
      <el-table-column label="库龄" align="center" prop="storageAge" />
      <el-table-column label="成本价" align="center" prop="costPrice" />
      <el-table-column label="回收价" align="center" prop="paybackPrice" />
      <el-table-column label="新增成本" align="center" prop="addPrice" />
      <el-table-column label="销售回收价" align="center" prop="salePaybackPrice" width="100px"/>
      <el-table-column label="销售人员" align="center" prop="saleUserName" />
      <el-table-column label="机况" align="center" prop="subrackDesc" show-overflow-tooltip width="100px"/>
      <el-table-column label="入库时间" align="center" prop="inboundTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.inboundTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库备注" align="center" prop="remark" />
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 详情 -->
    <el-dialog title="详情" :visible.sync="openDetail" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="30">
            <el-form-item label="品牌：">{{ form.brand }}</el-form-item>
          </el-col>
          <el-col :span="30">
            <el-form-item label="手机型号：">{{ form.model }}</el-form-item>
          </el-col>
          <el-col :span="30">
            <el-form-item label="型号类型：">{{ form.modelType }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="IMEI：">{{ form.imei }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数：">{{ form.memory }}，{{ form.colour }}，{{ form.buy }}，{{
                form.network
              }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机况：">{{ form.subrackDesc }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="补充说明：">{{ form.subrackOtherDesc }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetail = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="700px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules1" label-width="80px">
        <el-form-item label="新增成本" prop="addPrice">
          <el-input-number v-model="form.addPrice" placeholder="请输入新增成本"/>
        </el-form-item>
        <el-form-item label="仓库备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入仓库备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 正式仓调拨 -->
    <el-dialog :title="allotTitle" :visible.sync="allotOpen" width="700px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules2" label-width="80px">
        <el-form-item label="调出仓库" prop="warehouseName" v-if="this.type==1">
          <el-input v-model="form.warehouseName" disabled/>
        </el-form-item>
        <el-form-item label="调入仓库" prop="inWarehouseId" v-if="this.type==1">
          <el-select v-model="form.inWarehouseId" placeholder="请选择仓库" clearable size="small" style="width: 100%">
            <el-option v-for="dict in warehouseDatas"
                       :key="dict.id" :label="dict.name" :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报损原因" prop="breakageReason" v-if="this.type==2">
          <el-input v-model="form.breakageReason" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {pcDamage, pcAllot, createStorageFormalWarehouse, updateStorageFormalWarehouse, deleteStorageFormalWarehouse, getStorageFormalWarehouse, getStorageFormalWarehousePage, exportStorageFormalWarehouseExcel, importTemplateOrder } from "@/api/pekingfish/storageFormalWarehouse";
import {getWarehouseList} from "@/api/pekingfish/warehouse";
import { DICT_TYPE, getDictDatas } from "@/utils/dict";
import {getBaseHeader} from '@/utils/request'
import ImageUpload from '@/components/ImageUpload'
import ImagePreview from '@/components/ImagePreview'
import VideoUpload from "@/components/VideoUpload";
import Editor from "@/components/Editor";

export default {
  name: "StorageFormalWarehouse",
  components: {
    VideoUpload, Editor,
    ImageUpload, ImagePreview,
  },
  data() {
    return {

      // 发货导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/pekingfish/storage-formal-warehouse/importExcel'
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 正式仓列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        productCode: null,
        orderId: null,
        orderNo: null,
        merchantOrderNo: null,
        costPrice: null,
        storageAge: null,
        addPrice: null,
        paybackPrice: null,
        salePaybackPrice: null,
        inboundTime: [],
        saleUserId: null,
        saleUserNo: null,
        saleUserName: null,
        status: null,
        type: null,
        deductionAmount: null,
        reason: null,
        fileId: null,
        brand: null,
        mode: null,
        modelType: null,
        implosionId: null,
        colour: null,
        memory: null,
        buyId: null,
        networkId: null,
        warrantyId: null,
        idAccountLockId: null,
        frameId: null,
        screenId: null,
        mainboardId: null,
        screenShowId: null,
        cameraId: null,
        startingUpId: null,
        alityId: null,
        imei: null,
        reportImg: null,
        subrackDesc: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        remark: null,
        entrepotWarehouseCode: null,
        entrepotWarehouseName: null,
        breakageReason: null,
      },
      // 表单参数
      form: {
        operateType:""
      },
      // 表单校验
      rules: {
        //addPrice: [{ required: true, message: "订单id不能为空", trigger: "blur" }]
      },
      rules1: {
        addPrice: [{required: true, message: "新增成本不能为空", trigger: "blur"}]
      },
      rules2: {
        inWarehouseId: [{required: true, message: "调入仓库不能为空", trigger: "blur"}],
        breakageReason: [{required: true, message: "报损原因不能为空", trigger: "blur"}]
      },
      warehouseDatas:[],
      // 弹出层标题
      allotTitle: '',
      // 是否显示弹出层
      allotOpen: false,
      type:"",
      openDetail: false,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.condition_type),
// 选中数组
      ids: [],
// 非单个禁用
      single: true,
// 非多个禁用
      multiple: true,
// ===表格数据===
      productList: [],

    };
  },
  created() {
    this.getList();
    //仓库数据
    getWarehouseList().then(response => {
      this.warehouseDatas = response.data
    })
  },
  methods: {

    handleMinChange(value) {
      this.verification()
    },
    handleMaxChange(value) {
      this.verification()
    },
    //字段验证
    verification(){
      if(this.queryParams.minStorageAge>this.queryParams.maxStorageAge){
        this.$message.warning("起始数不能大于结束数");
        return false;
      }else{
        return true;
      }
    },

    /** 查询列表 */
    getList() {
      this.queryParams.isOutbound=0;
      this.loading = true;
      // 执行查询
      getStorageFormalWarehousePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log("多选框选中数据");
      this.ids = selection.map(item => item.id);// 需要根据数据情况调整id名称
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {

      this.form = {
        id: undefined,
        productCode: undefined,
        orderId: undefined,
        orderNo: undefined,
        merchantOrderNo: undefined,
        costPrice: undefined,
        storageAge: undefined,
        addPrice: undefined,
        paybackPrice: undefined,
        salePaybackPrice: undefined,
        inboundTime: undefined,
        saleUserId: undefined,
        saleUserNo: undefined,
        saleUserName: undefined,
        status: undefined,
        type: undefined,
        deductionAmount: undefined,
        reason: undefined,
        fileId: undefined,
        brand: undefined,
        mode: undefined,
        modelType: undefined,
        implosionId: undefined,
        colour: undefined,
        memory: undefined,
        buyId: undefined,
        networkId: undefined,
        warrantyId: undefined,
        idAccountLockId: undefined,
        frameId: undefined,
        screenId: undefined,
        mainboardId: undefined,
        screenShowId: undefined,
        cameraId: undefined,
        startingUpId: undefined,
        alityId: undefined,
        imei: undefined,
        reportImg: undefined,
        subrackDesc: undefined,
        warehouseCode: undefined,
        warehouseName: undefined,
        remark: undefined,
        entrepotWarehouseCode: undefined,
        entrepotWarehouseName: undefined,
        breakageReason: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加正式仓";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getStorageFormalWarehouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改正式仓";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateStorageFormalWarehouse(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createStorageFormalWarehouse(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除正式仓编号为"' + id + '"的数据项?').then(function() {
          return deleteStorageFormalWarehouse(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;

      if (!(this.ids=="" || this.ids==undefined)){
        console.log("this.ids:",this.ids)

        params.ids = this.ids.join(',');
      }
      this.$modal.confirm('是否确认导出所有正式仓数据项?').then(() => {
          this.exportLoading = true;
          return exportStorageFormalWarehouseExcel(params);
        }).then(response => {
          this.$download.excel(response, '正式仓.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    // 更多操作
    handleCommand(command, index, row) {
      switch (command) {
        case 'allot':
          this.doSomthing(row,1);//调拨
          break;
        case 'reportDamage':
          this.doSomthing(row,2);//报损
          break;
        default:
          break;
      }
    },
    /** 扣款按钮操作 */
    doSomthing(row,type) {
      this.type = type;
      this.reset();
      console.log("111:",this.type)
      getStorageFormalWarehouse(row.id).then(response => {
        this.form = response.data;
      });
      if (type==1){
        this.allotTitle = "调拨";
        this.form.operateType = "allot";
      }else if(type==2) {
        this.allotTitle = "报损";
        this.form.operateType = "damage";
      }
      this.allotOpen = true;
    },
    /** 扣款取消按钮 */
    cancel1() {
      this.allotOpen = false;
      this.reset();
    },
    /** 报损调拨提交按钮 */
    submitForm1() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        console.log("this.type:",+this.type)
        // 修改的提交
        if (this.type==1) {
          pcAllot(this.form).then(response => {
            this.$modal.msgSuccess("调拨成功");
            this.allotOpen = false;
            this.getList();
          });
          return;
        }else if (this.type==2) {
          pcDamage(this.form).then(response => {
            this.$modal.msgSuccess("报损成功");
            this.allotOpen = false;
            this.getList();
          });
          return;
        }
      });
    },

    checkoutNumRange (e, low) {
      const targetValue = e.target.value
      if (targetValue <= low && targetValue !== '') {
        this.$message.warning('只能输入大于0的正整数')
        e.target.value = ''
      }
    },
    handleView(row) {
      this.openDetail = true
      this.form = row
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "正式仓导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      importTemplateOrder().then(response => {
        this.$download.excel(response, '正式仓导导入模板.xls');
      });
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '创建成功数量：' + data.createUsernames.length;
      /*for (const username of data.createUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      }
      text += '<br />更新成功数量：' + data.updateUsernames.length;
      for (const username of data.updateUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      }
      text += '<br />更新失败数量：' + Object.keys(data.failureUsernames).length;
      for (const username in data.failureUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username + '：' + data.failureUsernames[username];
      }*/
      this.$alert(text, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
